
package com.gitee.jmash.oidc.oauth2.impl;

import com.gitee.jmash.oidc.oauth2.enums.GrantType;
import com.gitee.jmash.oidc.oauth2.enums.GrantWay;
import com.gitee.jmash.oidc.oauth2.models.ErrorResponse;
import com.gitee.jmash.oidc.oauth2.models.TokenPasswordModel;
import com.gitee.jmash.oidc.oauth2.models.TokenResponse;
import com.gitee.jmash.oidc.web.Constant;
import com.gitee.jmash.oidc.web.OidcMapper;
import com.gitee.jmash.rbac.RbacFactory;
import com.gitee.jmash.rbac.entity.TokenEntity;
import com.xyvcard.ops.OpsFactory;
import com.xyvcard.ops.entity.OpsClientEntity;
import jakarta.enterprise.context.Dependent;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.ws.rs.core.Response;
import jmash.rbac.protobuf.LoginReq;

/**
 * OAuth 2.0 更新令牌.
 *
 * @author CGD
 *
 */
@Dependent
public class OauthPasswordImpl {

  /** password --> access_token. */
  public Response token(@Valid TokenPasswordModel token, HttpServletRequest request) {

    // 1.验证GrantType
    if (!GrantType.password.equals(token.getGrantType())) {
      return ErrorResponse.createResponse("invalid_grant", "invalid_grant不匹配.");
    }
    // 2.验证clientId、clientSecret
    OpsClientEntity client = OpsFactory.getOpsClientRead(Constant.TENANT)
        .findBySecret(token.getClientId(), token.getClientSecret());
    if (client == null || !client.allowGrantWay(GrantWay.password.name())) {
      return ErrorResponse.createResponse("invalid_client", "client_id身份认证错误或授权方式不一致.");
    }
    // 3.验证用户名密码
    LoginReq req = LoginReq.newBuilder().setTenant(Constant.TENANT).setDirectoryId("jmash")
        .setUserName(token.getUsername()).setEncodePwd(token.getPassword())
        .setClientId(token.getClientId()).setScope("openid profile email phone address").build();
    TokenEntity tokenEntity = RbacFactory.getUserWrite(Constant.TENANT).login(req);

    TokenResponse resp = new TokenResponse();
    OidcMapper.INSTANCE.update(resp, tokenEntity);

    return Response.ok().entity(resp).build();
  }
}
